<template>
  <div>
    <el-tabs v-model="activeTab" @tab-click="tabClick" v-if="false">
      <el-tab-pane label="竞价报备" name="bidding"></el-tab-pane>
    </el-tabs>
    <el-container class="screening-box">
      <el-form :inline="true" :model="searchData" class="searchForm" ref="searchForm" :rules="rules" label-position="right" label-width="100px">
        <el-header class="screening-head">
          <div class="title">
            <i class="el-icon-search el-icon--left"></i>筛选查询
          </div>
          <div>
            <span class="toggle" v-show="showScreening" @click="showScreening=!showScreening">
              <i class="el-icon-arrow-up el-icon--left"></i>收起筛选
            </span>
            <span class="toggle" v-show="!showScreening" @click="showScreening=!showScreening">
              <i class="el-icon-arrow-down el-icon--left"></i>展开筛选
            </span>
            <el-button type="primary" class="tlwok-btn" @click="onSubmitForm('searchForm',searchFunc)">查询</el-button>
            <el-button type="primary" class="tlwok-btn" plain @click="onResetForm('searchForm',resetSearch)">重置</el-button>
          </div>
        </el-header>
        <el-main class="screening-body" v-show="showScreening">
          <el-form-item label="报备编号：" prop="filingNumber">
            <el-input v-model.number="searchData.filingNumber" maxlength="14" placeholder="请输入报备编号"></el-input>
          </el-form-item>
          <el-form-item :label="(activeTab == 'orders'?'点单':'竞价')+'平台：'" prop="purchasePlatformId">
            <el-select v-model="searchData.purchasePlatformId" :placeholder="'请选择'+(activeTab == 'orders'?'点单':'竞价')+'平台'">
              <el-option v-for="item in platformList" :key="item.id" :label="item.sourceName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="提交时间：" label-width="150px" prop="submitTime">
            <el-date-picker v-model="searchData.submitTime" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" align="right"></el-date-picker>
          </el-form-item>
          <el-form-item label="用户账户：" prop="registrarUserName">
            <el-input v-model="searchData.registrarUserName" placeholder="请输入用户账户"></el-input>
          </el-form-item>
          <template>
            <el-form-item v-if="activeTab == 'orders'" label="公司名称：" prop="registrarCompanyName">
              <el-input v-model="searchData.registrarCompanyName" placeholder="请输入公司名称"></el-input>
            </el-form-item>
            <el-form-item v-else label="项目编号：" prop="projectId">
              <el-input v-model.number="searchData.projectId" maxlength="20" placeholder="请输入项目编号"></el-input>
            </el-form-item>
          </template>
          <el-form-item :label="(activeTab == 'orders'?'项目报备':'竞价')+'截止时间：'" label-width="150px" prop="filingTime">
            <el-date-picker v-model="searchData.filingTime" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" align="right"></el-date-picker>
          </el-form-item>
        </el-main>
      </el-form>
    </el-container>
    <el-row class="btn-box">
      <template v-if="activeTab == 'orders'">
        <el-button v-for="item in typeList" :key="item.value" :type="item.active?'primary':''" @click="filterList(item)">
          {{item.desc}}
          (
          <span class="number">{{item.number}}</span>
          )
        </el-button>
      </template>
      <template v-else>
        <el-button v-for="item in typeList_b" :key="item.value" :type="item.active?'primary':''" @click="filterList(item)">
          {{item.desc}}
          (
          <span class="number">{{item.number}}</span>
          )
        </el-button>
      </template>
    </el-row>
    <div class="table-box">
      <div class="table-title">
        <span class="title">
          <i class="el-icon-notebook-2 el-icon--left"></i>报备记录
        </span>
        <div>
          <el-button class="filing-button" type="primary" @click="importList">导出所选报备单</el-button>
          <el-button v-if="activeTab!='orders'" class="filing-button" type="primary" plain @click="bulkRefuse">批量拒绝报备</el-button>
        </div>
      </div>
      <template>
        <el-table v-if="activeTab=='orders'" ref="multipleTable" :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange" :header-cell-style="tableHeaderColor" :cell-style="tableCellStyle">
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column prop="filingNumber" label="报备编号" width="110"></el-table-column>
          <el-table-column prop="registrarUserName" label="用户账户">
            <template slot-scope="scope">{{scope.row.registrarUserName }}</template>
          </el-table-column>
          <el-table-column prop="registrarCompanyName" label="公司名称">
            <template slot-scope="scope">{{scope.row.registrarCompanyName }}</template>
          </el-table-column>
          <el-table-column label="提交时间" width="95">
            <template slot-scope="scope">{{scope.row.createTime | dateFilter}}</template>
          </el-table-column>
          <el-table-column label="点单平台">
            <template slot-scope="scope">
              <el-row class="warning-text">{{scope.row.purchasePlatformName}}</el-row>
            </template>
          </el-table-column>
          <el-table-column label="项目报备时间">
            <template slot-scope="scope">
              <el-row>{{scope.row.registrarStartTime | dateFilterToDay}}</el-row>至
              <el-row>{{scope.row.registrarEndTime | dateFilterToDay}}</el-row>
            </template>
          </el-table-column>
          <el-table-column label="商品条数" width="90">
            <template slot-scope="scope">{{scope.row.goodsNums || 0}}条</template>
          </el-table-column>
          <el-table-column label="价格总计" width="120">
            <template slot-scope="scope">
              <el-row>挂网价：</el-row>
              <el-row>{{scope.row.totalSalesPrice | priceFilter}}元</el-row>
              <el-row>成交价：</el-row>
              <el-row>{{scope.row.totalFinalPrice | priceFilter}}元</el-row>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注">
            <template slot-scope="scope">{{scope.row.remark }}</template>
          </el-table-column>
          <el-table-column label="报备状态" width="100">
            <template slot-scope="scope">
              <div class="hasEdit" v-if="scope.row.modifyStatus">
                <span class="text">改</span>
              </div>
              <p :class="{'red':scope.row.status<4,'grey':scope.row.status>4}">{{ scope.row.status | statusFilterC1}}</p>
              <el-button @click.native.prevent="showLog(scope.row.id)" type="text" size="small">
                审核记录
                <i class="el-icon-arrow-right"></i>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140">
            <template slot-scope="scope">
              <div class="handler">
                <el-row>
                  <el-button @click.native.prevent="showDetail(scope.row.id)" type="text" size="small">查看详情</el-button>
                  <el-button :disabled="!(scope.row.status==3||scope.row.status==4)" @click.native.prevent="showRelatedOrder(scope.row.id)" type="text" size="small">关联信息</el-button>
                </el-row>
                <el-row>
                  <el-button @click.native.prevent="changeStatus(scope.row.id, scope.row.status)" type="text" size="small">{{ scope.row.status | statusHandlerFilter}}</el-button>
                  <el-button :disabled="scope.row.status>3" @click.native.prevent="refuseOrder(scope.row.id)" type="text" size="small">拒绝报备</el-button>
                </el-row>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-table v-else ref="multipleTable" :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange" :header-cell-style="tableHeaderColor" :cell-style="tableCellStyle" @sort-change="handleSortChange">
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column prop="filingNumber" label="报备编号" width="90"></el-table-column>
          <el-table-column prop="registrarUserName" label="用户账户">
            <template slot-scope="scope">{{scope.row.registrarUserName }}</template>
          </el-table-column>
          <el-table-column prop="companyName" label="公司名称">
            <template slot-scope="scope">{{scope.row.companyName }}</template>
          </el-table-column>
          <el-table-column prop="createTime" label="提交时间" width="102" sortable="custom">
            <template slot-scope="scope">{{scope.row.createTime | dateFilter}}</template>
          </el-table-column>
          <el-table-column prop="bidPlatformName" label="竞价平台">
            <template slot-scope="scope">{{scope.row.bidPlatformName}}</template>
          </el-table-column>
          <el-table-column prop="projectId" label="项目编号" width="100">
            <template slot-scope="scope">{{scope.row.projectId}}</template>
          </el-table-column>
          <el-table-column prop="bidEndTime" label="竞价截止时间" width="100" sortable="custom">
            <template slot-scope="scope">{{scope.row.bidEndTime | dateFilter}}</template>
          </el-table-column>
          <el-table-column label="商品条数" width="100">
            <template slot-scope="scope">{{scope.row.goodSkuNum || 0}}条</template>
          </el-table-column>
          <el-table-column label="商品总价" width="110">
            <template slot-scope="scope">{{scope.row.goodTotalPrice }}元</template>
          </el-table-column>
          <el-table-column prop="remark" label="备注">
            <template slot-scope="scope">{{scope.row.remark }}</template>
          </el-table-column>
          <el-table-column label="报备状态" width="100">
            <template slot-scope="scope">
              <div class="hasEdit" v-if="scope.row.isUpdate==0">
                <span class="text">改</span>
              </div>
              <p :class="{'red':scope.row.filingState==1,'orange':scope.row.filingState==2,'grey':scope.row.filingState>4}">{{ scope.row.filingState | statusListC1_b}}</p>
              <el-button @click.native.prevent="showLog(scope.row.id)" type="text" size="small">
                审核记录
                <i class="el-icon-arrow-right"></i>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140">
            <template slot-scope="scope">
              <div class="handler">
                <el-row>
                  <el-button @click.native.prevent="showDetail(scope.row.id)" type="text" size="small">查看详情</el-button>
                  <el-button v-if="scope.row.filingState>0&&scope.row.filingState<4" @click.native.prevent="changeStatus(scope.row.id, scope.row.filingState)" type="text" size="small">{{ scope.row.filingState | statusBHandlerFilter }}</el-button>
                </el-row>
                <el-row v-if="scope.row.filingState>0&&scope.row.filingState<4">
                  <div class="occupation"></div>
                  <el-button v-if="scope.row.filingState==3" @click.native.prevent="changeStatus(scope.row.id,5)" type="text" size="small">竞价失败</el-button>
                  <el-button v-if="scope.row.filingState==1||scope.row.filingState==2" @click.native.prevent="refuseOrder(scope.row.id)" type="text" size="small">拒绝报备</el-button>
                </el-row>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div class="table-handler">
        <div></div>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="pageSizeArr" :page-size="currentSize" layout="total, sizes, prev, pager, next, jumper" :total="totalSize"></el-pagination>
      </div>
    </div>
    <el-dialog title="审核记录" :visible.sync="logsDialogVisible" width="60%">
      <el-table :data="logData" border :header-cell-style="tableHeaderColor" max-height="500">
        <el-table-column label="时间" width="150">
          <template slot-scope="scope">{{scope.row.operatorTime | dateFilter}}</template>
        </el-table-column>
        <el-table-column property="operator" label="操作人" width="150" align="center"></el-table-column>
        <el-table-column label="审核状态" width="100" align="center">
          <template slot-scope="scope">
            <span v-if="activeTab=='orders'">{{scope.row.auditStatus | statusFilterC2}}</span>
            <span v-else>{{scope.row.auditStatus | statusFilterC2_b}}</span>
          </template>
        </el-table-column>
        <el-table-column label="详情">
          <template slot-scope="scope">
            <el-row v-for="(item,index) in evalData(scope.row.auditDetail)" :key="index">{{item.auditDetail}}</el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="拒绝报备" :visible.sync="refuseDialogVisible">
      <el-form :model="refuse" ref="refuse">
        <el-form-item label="拒绝原因：" prop="result" required :rules="[
            { required: true, message: '请输入拒绝原因', trigger: 'blur' },
            { max: 100, message: '已超出字数限制', trigger: ['blur', 'change'] }
          ]">
          <el-input v-model.trim="refuse.result" autocomplete="off" type="textarea" :rows="5" maxlength="100" show-word-limit placeholder="请输入拒绝原因"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="isBulkRefuse" type="primary" @click="onSubmitForm('refuse',submitBulkRefuse)">确 定</el-button>
        <el-button v-else type="primary" @click="onSubmitForm('refuse',submitForm)">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="关联信息" width="800px" :visible.sync="relatedDialogVisible" class="related-dialog">
      <div class="skuTitle">关联订单：</div>
      <el-form ref="relatedOrderForm" class="relatedOrderForm" label-width="100px">
        <div class="form-item newFormItem" v-if="relatedOrderlist.length>0">
          <el-form-item v-for="(order, index) in relatedOrderlist" :key="index" :class="{'is-error':!!order.errorMsg}">
            <!-- :rules="[{required: true, message: '订单号不能为空', trigger: 'blur'},{type:'number', message: '订单号为数字', trigger: 'change'}]" -->
            <div class="el-step__icon is-text">
              <div class="el-step__icon-inner">{{index+1}}</div>
            </div>
            <template v-if="order.edit">
              <el-input size="small" v-model="order.orderId" placeholder="请输入自营店订单号"></el-input>
              <el-button size="small" type="primary" @click.prevent="saveOrder(order)">保存</el-button>
            </template>
            <template v-if="!order.edit">
              <div class="el-input">{{order.orderId}}</div>
              <el-button size="small" type="primary" @click.prevent="editOrder(order)">编辑</el-button>
            </template>
            <el-button size="small" type="primary" plain @click.prevent="removeOrder(order,index)">删除</el-button>
            <div class="el-form-item__error" v-show="order.edit">{{order.errorMsg}}</div>

          </el-form-item>
        </div>

        <el-form-item v-if="showAddBtn">
          <el-button @click="addOrder" class="add-related-order" icon="el-icon-plus">增加关联订单</el-button>
        </el-form-item>
      </el-form>

      <!-- 新增SKU链接输入及展示 -->
      <div class="skuList">
        <div class="skuTitle">关联SKU链接：</div>

        <el-table :data="skuTableData" border class="skuTable" style="width:100%">
          <el-table-column prop="goodsName" align="center" label="商品名称" width="300"></el-table-column>
          <el-table-column prop="unit" align="center" label="单位" width="80"></el-table-column>
          <el-table-column label="商品链接" align="center">
            <template slot-scope="scope">
              <el-input size="small" v-model="scope.row.productLink" placeholder="请输入链接"></el-input>
            </template>
          </el-table-column>
        </el-table>

        <div class="skuSubmit">
          <el-button size="small" class="submitBtn" type="primary" @click="skuSubmit">确认提交</el-button>
        </div>

      </div>

    </el-dialog>
  </div>
</template>

<script>
import dict from '@/lib/dict.js'
console.log('dict', dict)
export default {
  name: 'OSSFiling',
  data() {
    let typeListFun = function(filingType) {
      let typeList = []
      if (filingType == 'bidding') {
        typeList = [{ desc: '全部报备', code: '' }, ...dict.statusListC1_b]
      } else {
        typeList = [{ desc: '全部报备', code: '' }, ...dict.statusListC1]
      }
      typeList.map(item => {
        item.number = 0
        item.active = false
      })
      return typeList
    }
    return {
      activeTab: 'bidding',
      /** 订单报备 **/
      searchData: {
        status: null,
        filingNumber: '',
        purchasePlatformId: null,
        submitTime: '',
        filingTime: '',
        updateTime: '',
        registrarUserName: null,
        registrarUserName: null,
        registrarUserName: null,
        registrarCompanyName: null,
        projectId: null,
      },
      showScreening: true,
      tableData: [],
      checkAll: false,
      multipleSelection: [],
      currentPage: 1,
      currentSize: 10,
      pageSizeArr: [10, 20, 30, 40],
      totalSize: 0,
      typeList: typeListFun(),
      platformList: [{ id: null, sourceName: '请选择' }],
      rules: { },
      logData: [],
      logsDialogVisible: false,
      refuseDialogVisible: false,
      relatedDialogVisible: false,
      refuse: { result: '' },
      relatedOrderlist: [],
      activeFilingId: '',
      /** 竞价报备 **/
      typeList_b: typeListFun('bidding'),
      isBulkRefuse: false,
      // 新增sku链接table
      skuTableData: [],
    }
  },
  filters: {
    statusHandlerFilter (val) {
      val = parseInt(val)
      switch (val) {
        case 1:
          return '通过审核'
          break
        case 2:
          return '确认上架'
          break
        case 3:
          return '完成采购'
          break

        default:
          return ''
          break
      }
    },
    statusBHandlerFilter(val) {
      val = parseInt(val)
      switch (val) {
        case 1:
          return '通过审核'
          break
        case 2:
          return '完成报价'
          break
        case 3:
          return '竞价成功'
          break

        default:
          return ''
          break
      }
    },
  },
  computed: {
    showAddBtn () {
      return this.relatedOrderlist.length < 5
    },
  },
  watch: {
    /**
     * 改变全选状态
     */
    multipleSelection (obj) {
      if (obj.length == this.tableData.length) this.checkAll = true
      else this.checkAll = false
    },
  },
  methods: {
    tabClick(tab, event) {
      this.onResetForm('searchForm', this.resetSearch)
      this.resetSearch()
      this.resetPageData()
      if (tab.name == 'orders') this.filterList(this.typeList[0])
      else this.filterList(this.typeList_b[0])
    },
    // 获取平台信息
    getPlatform () {
      this.$axios
        .get('/api/manage/project/getAllProjectInfo')
        .then(res => {
          if (res.success) {
            let list = []
            res.result.forEach(item => {
              list.push({id : item.projectId , sourceName: item.name})
            })
            this.platformList = list
          }
          else this.$message.error(res.desc)
        })
    },
    /**
     * 截取时间
     */
    spliteTime() {
      if (this.searchData.submitTime && this.searchData.submitTime.length > 0) {
        this.searchData.commitStartTime = this.searchData.submitTime[0]
        this.searchData.commitEndTime = this.searchData.submitTime[1]
      } else {
        this.searchData.commitStartTime = null
        this.searchData.commitEndTime = null
      }
      if (this.searchData.filingTime && this.searchData.filingTime.length > 0) {
        this.searchData.filingStartTime = this.searchData.filingTime[0]
        this.searchData.filingEndTime = this.searchData.filingTime[1]
      } else {
        this.searchData.filingStartTime = null
        this.searchData.filingEndTime = null
      }
      if (this.searchData.updateTime && this.searchData.updateTime.length > 0) {
        this.searchData.updateStartTime = this.searchData.updateTime[0]
        this.searchData.updateEndTime = this.searchData.updateTime[1]
      } else {
        this.searchData.updateStartTime = null
        this.searchData.updateEndTime = null
      }
    },
    /**
     * 查询按钮
     */
    searchFunc() {
      this.showList()
      this.currentPage = 1
    },
    /**
     * 筛选查询
     */
    showList () {
      this.spliteTime()
      if (this.activeTab == 'orders') {
        this.$axios
          .post(
            `/api/manage/audit/getFilingAuditInfo?startPage=${this.currentPage}&size=${this.currentSize}`,
            this.searchData
          )
          .then(res => {
            if (res.success) {
              this.tableData = res.result.filingAuditInfo.list
              this.totalSize = res.result.filingAuditInfo.total
              // 获取状态对应报备数量
              let _typeList = res.result.filingStatus
              this.typeList.map((item, index) => {
                switch (item.code) {
                  case '1':
                    item.number = _typeList.pendingReview
                    break
                  case '2':
                    item.number = _typeList.waitShelf
                    break
                  case '3':
                    item.number = _typeList.alreadyShelf
                    break
                  case '4':
                    item.number = _typeList.finished
                    break
                  case '5':
                    item.number = _typeList.noPass
                    break
                  case '6':
                    item.number = _typeList.cancel
                    break
                  default:
                    item.number = _typeList.allCount
                    break
                }
              })
            } else {
              this.$message.error(res.desc)
              this.resetPageData()
            }
          })
      } else {
        let _param = {
          filingNumber: this.searchData.filingNumber,
          bidPlatformId: this.searchData.purchasePlatformId,
          projectId: this.searchData.projectId,
          registrarName: this.searchData.registrarUserName,
          commitStartTime: this.searchData.commitStartTime,
          commitEndTime: this.searchData.commitEndTime,
          bidStartTime: this.searchData.filingStartTime,
          bidEndTime: this.searchData.filingEndTime,
          filingState: this.searchData.status,
          commitTimeSort: this.searchData.commitTimeSort,
          endBidTimeSort: this.searchData.endBidTimeSort,
          cancelStartTime: this.searchData.updateStartTime,
          cancelEndTime: this.searchData.updateEndTime,
        }

        this.$axios
          .post(
            `/api/manage/audit/queryManageBidFilingList?startPage=${this.currentPage}&size=${this.currentSize}`,
            _param
          )
          .then(res => {
            if (res.success) {
              this.tableData = res.result.filingBidBaseInfoPageResult.list
              this.totalSize = res.result.filingBidBaseInfoPageResult.total
              // 获取状态对应报备数量
              let _typeList = res.result.bidBaseInfoCount
              this.typeList_b.map((item, index) => {
                switch (item.code) {
                  case '1':
                    item.number = _typeList.waitAuditing
                    break
                  case '2':
                    item.number = _typeList.waitBid
                    break
                  case '3':
                    item.number = _typeList.onBid
                    break
                  case '4':
                    item.number = _typeList.bidSuccess
                    break
                  case '5':
                    item.number = _typeList.bidFailed
                    break
                  case '6':
                    item.number = _typeList.reviewFailed
                    break
                  case '7':
                    item.number = _typeList.providerCancel
                    break
                  default:
                    item.number = _typeList.totalCount
                    break
                }
              })
            } else {
              this.$message.error(res.desc)
              this.resetPageData()
            }
          })
      }
    },
    /**
     * 查看报备详情
     */
    showDetail(id) {
      let  pathName = 'BidFilingDetail'

      let { href } = this.$router.resolve({
        name: pathName,
        query: { id: id },
      })
      window.open(href, '_blank')
    },
    /**
     * 审核记录
     */
    showLog(id) {
      let url = '/api/manage/auditRecord/getFilingAuditRecordList'
      if (this.activeTab == 'bidding')
        url = '/api/manage/auditRecord/getBidFilingAuditRecordList'
      this.logsDialogVisible = true
      this.$axios.get(url + '?filingId=' + id).then(res => {
        if (res.success) this.logData = res.result
        else this.$message.error(res.desc)
      })
    },
    /**
     * 查看关联订单
     */
    showRelatedOrder (id) {
      this.relatedDialogVisible = true
      this.$axios
        .get('/api/manage/associateOrder/getAssociateOrdersList?id=' + id)
        .then(res => {
          if (res.success) {
            let result = res.result
            result.map(item => {
              item.errorMsg = ''
              item.edit = false
            })
            this.relatedOrderlist = Object.assign([], result)
            this.activeFilingId = id
          } else this.$message.error(res.desc)
        })
      this.getSkulist(id)
    },
    /**
     * 根据状态操作订单
     */
    changeStatus (id, status) {
      status = parseInt(status)
      if (this.activeTab == 'orders') {
        let arr = ['通过', '上架', '完成', '拒绝']
        let msg = arr[status - 1] || ''

        if (msg)
          this.$confirm(`确认要${msg}此笔报备订单吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              let data = { id: id, status: status + 1 }
              if (status == 4) {
                data.refuseCause = this.refuse.result
              }

              this.$axios
                .post('/api/manage/audit/updateFilingAuditStatus', data)
                .then(res => {
                  if (res.success) {
                    this.$message({
                      type: 'success',
                      message: `${msg}报备订单成功`,
                    })
                    if (status == 4) {
                      this.refuseDialogVisible = false
                    }
                    this.showList()
                  } else
                    this.$message({
                      type: 'error',
                      message: res.desc
                    })
                })
            })
            .catch(() => {})
      } else {
        let arr = [
          '要通过此笔竞价报备单',
          '此笔竞价报备单已完成报价了',
          '此笔竞价报备单对应报价最终竞价成功',
          '',
          '此笔竞价报备单对应报价最终竞价失败',
          '要拒绝此笔竞价报备单',
        ]
        let msg = arr[status - 1] || ''
        if (msg)
          this.$confirm(`确认${msg}吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              let data = {
                id: id,
                filingState: status < 4 ? status + 1 : status,
              }
              if (status == 6) {
                data.refuseCause = this.refuse.result
              }

              this.$axios
                .post('/api/manage/audit/updateBidFilingAuditStatus', data)
                .then(res => {
                  if (res.success) {
                    this.$message({
                      type: 'success',
                      message: res.result,
                    })
                    if (status == 6) {
                      this.refuseDialogVisible = false
                    }
                    this.showList()
                  } else
                    this.$message({
                      type: 'error',
                      message: res.desc,
                    })
                })
            })
            .catch(() => {})
      }
    },
    /**
     * 拒绝报备按钮
     */
    refuseOrder(id) {
      this.refuseDialogVisible = true
      this.activeFilingId = id
      this.onResetForm('refuse')
    },
    /**
     * 拒绝报备原因提交
     */
    submitForm() {
      let status = 4
      if (this.activeTab == 'bidding') status = 6
      this.changeStatus(this.activeFilingId, status)
    },
    /**
     * 导出所选报备单
     */
    importList() {
      let arr = []
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: 'error',
          message: '您还未选择报备单',
        })
        return
      }
      this.multipleSelection.map(item => {
        arr.push(item.id)
      })

      let url = '/api/manage/exportFilingListExcel?exportIds='
      if (this.activeTab == 'bidding') {
        url = '/api/manage/exportBidFilingInfoListExcel?filingIds='
      }
      window.location.href =
        window.globalConfig.apiUrl +
        url +
        encodeURIComponent(JSON.stringify(arr))
    },
    /**
     * 批量拒绝所选报备单
     */
    bulkRefuse() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: 'error',
          message: '您还未选择报备单',
        })
        return
      }
      this.refuseDialogVisible = true
      this.isBulkRefuse = true
      this.onResetForm('refuse')
    },
    /**
     * 批量拒绝报备原因
     */
    submitBulkRefuse() {
      if (!this.refuse.result) return false

      this.$confirm(`确认要批量拒绝已选报备订单吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let arr = []
          this.refuseDialogVisible = false
          this.multipleSelection.map(item => {
            arr.push({
              id: item.id,
              filingState: 6,
              refuseCause: this.refuse.result,
            })
          })
          this.$axios
            .post('/api/manage/audit/batchUpdateBidFilingAuditStatus', arr)
            .then(res => {
              this.isBulkRefuse = false
              if (res.success) {
                this.$message({
                  type: 'success',
                  message: '批量拒绝报备成功',
                })
                this.showList()
              } else
                this.$message({
                  type: 'error',
                  message: res.desc,
                })
            })
        })
        .catch(() => {})
    },
    /**
     * 获取table已选择数据
     */
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    /**
     * 切换每页显示条数
     */
    handleSizeChange(val) {
      this.currentSize = val
      this.currentPage = 1
      this.showList()
    },
    /**
     * 翻页
     */
    handleCurrentChange(val) {
      this.currentPage = val
      this.showList()
    },
    // 修改table header的背景色
    tableHeaderColor ({ row, column, rowIndex, columnIndex }) {
      return 'background-color: #f5f5f5;color: #333;font-weight: bold;text-align:center'
    },
    // 修改table tr行的样式
    tableCellStyle ({ row, column, rowIndex, columnIndex }) {
      return 'text-align:center'
    },
    // 表格的排序条件发生变化
    handleSortChange(param) {
      if (param.prop == 'createTime') {
        this.searchData.endBidTimeSort = null
        if (param.order == 'ascending') {
          this.searchData.commitTimeSort = 'asc'
        } else if (param.order == 'descending') {
          this.searchData.commitTimeSort = 'desc'
        } else {
          this.searchData.commitTimeSort = null
        }
      } else if (param.prop == 'bidEndTime') {
        this.searchData.commitTimeSort = null
        if (param.order == 'ascending') {
          this.searchData.endBidTimeSort = 'asc'
        } else if (param.order == 'descending') {
          this.searchData.endBidTimeSort = 'desc'
        } else {
          this.searchData.endBidTimeSort = null
        }
      }
      this.showList()
    },
    /**
     * 报备状态筛选
     * filingType 报备类型：0||null-订单  1-竞价
     */
    filterList(status) {
      let _typeList = this.typeList
      if (this.activeTab == 'bidding') _typeList = this.typeList_b
      _typeList.map(item => {
        item.active = false
      })
      status.active = true
      this.searchData.status = status.code
      this.currentPage = 1
      this.showList()
    },
    /**
     * 全选按钮
     */
    toggleSelection () {
      if (this.checkAll) {
        this.tableData.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row, this.checkAll)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    /**
     * 增加关联订单
     */
    addOrder () {
      this.relatedOrderlist.push({
        orderId: '',
        id: '',
        edit: true,
        errorMsg: '',
      })
    },
    /**
     * 编辑订单
     */
    editOrder (order) {
      order.edit = true
    },
    /**
     * 保存订单
     */
    saveOrder (order) {
      if (!order.orderId) {
        order.errorMsg = '请输入自营店订单号'
        return
      }
      // if (!parseInt(order.orderId)) {
      //   order.errorMsg = '请输入正确的订单号'
      //   return
      // }

      if (order.id) {
        // 修改
        this.$axios
          .post('/api/manage/associateOrder/updateAssociateOrder', {
            id: order.id,
            orderId: order.orderId,
          })
          .then(res => {
            if (res.success) {
              this.$message({ type: 'success', message: '订单修改成功' })
              order.edit = false
            } else this.$message.error(res.desc)
          })
      } else {
        // 新增
        this.$axios
          .post('/api/manage/associateOrder/insertAssociateOrder', {
            filingId: this.activeFilingId,
            orderId: order.orderId,
          })
          .then(res => {
            if (res.success) {
              this.$message({ type: 'success', message: '订单保存成功' })
              order.edit = false
            } else this.$message.error(res.desc)
          })
      }
    },
    /**
     * 删除订单
     */
    removeOrder (order, index) {
      if (order.id)
        this.$confirm('确认要删除该条订单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.$axios
              .get(
                '/api/manage/associateOrder/deleteAssociateOrderById?id=' +
                order.id
              )
              .then(res => {
                if (res.success) {
                  this.$message({
                    type: 'success',
                    message: '删除成功!',
                  })
                  this.relatedOrderlist.splice(index, 1)
                } else this.$message.error(res.desc)
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      else this.relatedOrderlist.splice(index, 1)
    },
    /**
     * 天数计算
     */
    AddDays (num) {
      var newdate = new Date()
      var newtimems = newdate.getTime() - num * 24 * 60 * 60 * 1000
      newdate.setTime(newtimems)
      let m = newdate.getMonth() + 1
      let d = newdate.getDate()
      m < 10 && (m = '0' + m)
      d < 10 && (d = '0' + d)
      var time = newdate.getFullYear() + '-' + m + '-' + d
      return time
    },
     /**
     * @name: 获取list数据
     * @param {type}
     * @return:
     */
    getSkulist(id) {
      this.$axios
        .get('/api/manage/audit/queryAuditGoodsRelevanceDetail?id=' + id)
        .then(resp => {
          if (resp.success) {
            this.skuTableData = resp.result
          }
        })
    },
    /**
     * @name: 关联信息提交
     * @param {type}
     * @return:
     */
    skuSubmit() {
      if (this.skuTableData.length > 0) {
        let params = []
        this.skuTableData.forEach(item => {
          // if (item.productLink) {
          let obj = {}
          obj['id'] = item.id
          obj['productLink'] = item.productLink
          params.push(obj)
          // }
        })
        this.$axios
          .post('/api/manage/audit/updateBatchFilingAuditProductLink', params)
          .then(resp => {
            if (resp.success) {
              this.$message.success(resp.result)
              this.relatedDialogVisible = false
            } else {
              this.$message.error(resp.desc)
            }
          })
      } else {
        this.$message.error('暂无数据可提交')
      }
    },
    /**
     * 重置按钮回调方法
     */
    resetSearch() {
      this.searchData.status = null
      this.searchData.submitTime = ''
      this.searchData.updateTime = ''
      let _typeList = this.typeList
      if (this.activeTab == 'bidding') _typeList = this.typeList_b
      _typeList.map(item => {
        item.active = false
      })
      _typeList[0].active = true
    },
    /**
     * 重置页面数据
     */
    resetPageData() {
      this.tableData = []
      this.currentSize = 10
      this.currentPage = 1
      this.totalSize = 0
      this.checkAll = false
    },
  },
  created () {
    let _status = this.$route.query.status

    if (this.$route.query.filingType) {
      // 竞价报备
      this.activeTab = 'bidding'
    }

    _status && (this.searchData.status = _status)

    if (this.$route.query.days >= 0) {
      let _days = parseInt(this.$route.query.days) || 0

      let _startDate = this.AddDays(_days) + ' 00:00:00'
      let _endDate =
        this.formatDate(new Date().getTime(), 'YY-MM-DD') + ' 23:59:59'

      switch (parseInt(_status)) {
        case 0: //查询全部
          this.searchData.submitTime = [_startDate, _endDate]
          break
        case 6:
        case 7: //查询服务商取消
          this.searchData.updateTime = [_startDate, _endDate]
          break

        default:
          break
      }
    }
    this.getPlatform()
  },
  mounted() {
    let _typeList = this.typeList
    if (this.activeTab == 'bidding') _typeList = this.typeList_b
    this.filterList(_typeList[parseInt(this.searchData.status) || 0])
  },
}
</script>

<style lang="less" scoped>
.title {
  font-weight: bold;
}
.grey {
  color: #bbb;
}
.red {
  color: red;
}
.orange {
  color: #ffac37;
}
.screening-box {
  border: 1px solid #ddd;
  .searchForm {
    width: 100%;
  }
}
.screening-head {
  background: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .toggle {
    cursor: pointer;
    margin-right: 50px;
  }
}
.screening-body {
  border-top: 1px solid #ddd;
}
.btn-box {
  margin-top: 40px;
  .number {
    color: red;
  }
  .el-button--primary {
    .number {
      color: #fff;
    }
  }
}
.table-title {
  height: 47px;
  line-height: 47px;
  padding: 0 15px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.table-box {
  border: 1px solid #ddd;
  margin-top: 10px;
}
.table-handler {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
  .check-all {
    margin-right: 20px;
  }
}
.hasEdit {
  position: absolute;
  top: 0;
  left: 0;
  &::before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    border-top: 30px solid red;
    border-right: 30px solid transparent;
  }
  .text {
    position: absolute;
    top: -3px;
    left: 2px;
    color: #fff;
    font-size: 12px;
  }
}
.el-input,
.el-select {
  width: 200px;
}
.handler {
  .el-button {
    width: 50px;
  }
}
.form-item {
  .el-step__icon {
    font-size: 14px;
    position: absolute;
    left: -40px;
    top: 8px;
  }
  .el-input {
    margin-right: 10px;
    width: 160px;
  }
}
.newFormItem {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  /deep/.el-form-item__content {
    margin-left: 50px !important;
  }
}
.add-related-order {
  width: 80%;
  margin-top: 30px;
}
.skuTitle {
  color: #101010;
  margin: 10px 0;
  font-weight: 600;
}
// 新增样式
.skuTable {
  max-height: 300px;
  overflow-y: auto;
  /deep/.has-gutter th .cell {
    color: #101010;
  }
  .el-input {
    width: 280px;
  }
}
.skuSubmit {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 20px;
  margin-right: 20px;
  .submitBtn {
    padding: 9px 30px;
  }
}

/deep/.el-dialog__header {
  border-bottom: 1px solid #bbb;
}
/deep/.el-dialog__body {
  padding-top: 10px;
}
/deep/ .el-tabs__item {
  font-weight: 600;
}
.occupation {
  width: 60px;
  display: inline-block;
  line-height: 1;
}
</style>
